//package com.qzsoft.component;
//
//import io.netty.bootstrap.Bootstrap;
//import io.netty.channel.*;
//import io.netty.channel.nio.NioEventLoopGroup;
//import io.netty.channel.socket.SocketChannel;
//import io.netty.channel.socket.nio.NioSocketChannel;
//import io.netty.handler.codec.bytes.ByteArrayDecoder;
//import io.netty.handler.codec.bytes.ByteArrayEncoder;
//import org.springframework.stereotype.Component;
//
//import javax.annotation.PostConstruct;
//import javax.annotation.PreDestroy;
//import java.util.concurrent.TimeUnit;
//
//@Component
//public class NettyTcpClient {
//    private final String host = "192.168.1.1"; // DTU的IP地址
//    private final int port = 9876;             // DTU的监听端口
//    private final int retryInterval = 5;       // 重试间隔（秒）
//    private EventLoopGroup group;
//    private Channel channel;
//
//    @PostConstruct
//    public void start() {
//        group = new NioEventLoopGroup();
//
//        try {
//            Bootstrap b = new Bootstrap();
//            b.group(group)
//                    .channel(NioSocketChannel.class)
//                    .handler(new ChannelInitializer<SocketChannel>() {
//                        @Override
//                        protected void initChannel(SocketChannel ch) {
//                            ch.pipeline().addLast(new ByteArrayDecoder(), new ByteArrayEncoder(), new TcpClientHandler());
//                        }
//                    });
//
//            // 异步连接并重试
//            b.connect(host, port).addListener(future -> {
//                if (future.isSuccess()) {
//                    channel = ((ChannelFuture) future).channel();
//                    System.out.println("TCP客户端已连接到：" + host + ":" + port);
//                } else {
//                    System.err.println("连接失败：" + future.cause().getMessage());
//                    group.schedule(this::start, retryInterval, TimeUnit.SECONDS);
//                }
//            });
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
//
////    public void sendCommand(byte[] command) {
////        if (channel != null && channel.isActive()) {
////            channel.writeAndFlush(command);
////            String s = "";
////            for(int i = 0;i<command.length;i++){
////                s += String.valueOf(command[i]);
////            }
////            System.out.println("发送命令5555:" + s);
////        } else {
////            System.err.println("无法发送命令：未连接到DTU");
////        }
////    }
//
//    @PreDestroy
//    public void stop() {
//        if (channel != null) {
//            channel.close();
//        }
//        group.shutdownGracefully();
//        System.out.println("TCP客户端已关闭");
//    }
//}